package com.tanhua.server.service;


import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.domain.UserInfo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.vo.ErrorResult;
import com.tanhua.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {
    @DubboReference
    private UserInfoApi userInfoApiImpl;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;




    public void save(UserInfo userInfo) {
        userInfoApiImpl.save(userInfo);
    }

    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        boolean detect = aipFaceTemplate.detect(imageUrl);
        if (!detect){
            throw new BusinessException(ErrorResult.faceError());
        }else {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfoApiImpl.update(userInfo);
        }
    }

    public UserInfoVo getById(Long userId) {
        UserInfo userInfo = userInfoApiImpl.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        if (userInfo.getAge() != null){
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    /**
     * 更新用户资料
     * @param userInfo
     */
    public void updateUserInfo(UserInfo userInfo) {
        userInfoApiImpl.update(userInfo);
    }
}
